package com.stu.manager.studentscoremanagersys.Utils;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.stu.manager.studentscoremanagersys.dto.JWTManagerDTO;
import com.stu.manager.studentscoremanagersys.res.Result;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;

@Slf4j
public class JWTUtil {

    public static final String SECREAT  = "com.stu.manager.studentscoremanagersys";

    /**
     * 生成token
     * @param t 泛型
     * @param <T> dto
     * @return token
     */
    public static<T> String getToken(T t){
        //定义过期时间 ,一个月过期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,1);
        //创建
        JWTCreator.Builder builder = JWT.create()
        //申明；id=123，username=admin
                .withClaim(t.getClass().getSimpleName(), JSON.toJSONString(t));
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SECREAT));
        return token;
    }

    /**
     * 用来校验token是否合法
     * @param tokenVertity
     * @return
     */
    public static Result<DecodedJWT> vali(String tokenVertity) {
        String errorMsg;
        try {
            DecodedJWT decodeJwt = JWT.require(Algorithm.HMAC256(SECREAT)).build()
                    .verify(tokenVertity);
            return Result.buildScuess(decodeJwt);
        }catch (SignatureVerificationException e){
            errorMsg = "签名不匹配";
           log.error(errorMsg,e);
        }catch (AlgorithmMismatchException e){
            errorMsg = "算法不匹配";
            log.error(errorMsg,e);
        }catch (TokenExpiredException e){
            errorMsg = "令牌过期";
            log.error(errorMsg,e);
        }catch (InvalidClaimException e){
            errorMsg = "申明无效";
            log.error(errorMsg,e);
        }catch (Exception e){
            errorMsg = "其他错误";
            log.error(errorMsg,e);
        }
        return Result.buildFailure(errorMsg);

    }

    /**
     * 解析token
     * @param DecodedJWT
     * @param 类型
     * @return
     */
    public static<T> T parse(DecodedJWT decodedJWT, Class<T> cla) {
        Claim clim = decodedJWT.getClaim(cla.getSimpleName());
        if (clim== null){
            return null;
        }
        //tostring是序列化为字符串
        //asString是格式化为字符串
        return JSON.parseObject(clim.asString(),cla);
    }
}
